package com.ynny.usermanager.controller;

import com.ynny.usermanager.dao.UserDao;
import com.ynny.usermanager.entity.R;
import com.ynny.usermanager.entity.User;
import com.ynny.usermanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserDao userDao;
    @Autowired
    UserService userService;

    @GetMapping("{id}")
    public R get(@PathVariable(name = "id") Integer id) {

        System.out.println("获取的id：" + id);

        User user = userDao.selectUserById(id);
        if (user == null) {
            new R(201, "查询无果", null);
        }

        return new R(200, "查询成功", user);
    }

    //查询所有用户
    @RequestMapping("/list")
    public R list() {

        //模拟集合数据
        List<User> users = userDao.selectAllUsers();

        return new R(200, "查询成功", users);
    }

    @RequestMapping("/add")
    public R add(@RequestBody User user) {
        System.out.println("request:----》" + user);
        //添加用户 判断用户名是否存在
        int i = userService.saveUser(user);

        if (i == 200) {
            return new R(200, "添加成功", user.getUsername());
        } else if (i == 202) {
            return new R(202, "用户名已经存在", null);
        }
        return new R(503, "添加失败", null);
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable(name = "id") Integer id) {

        System.out.println("删除的id：" + id);

        int i = userDao.deleteUser(id);

        if (i == 200) {
            return new R(200, "删除成功", id);
        }
        return new R(503, "删除失败", null);
    }

    @PutMapping("/update")
    public R update(@RequestBody User user) {
        System.out.println("需要修改的用户" + user);
        int i = userDao.updateUser(user);
        if (i > 0) {
            return new R(200, "修改成功", user);
        }
        return new R(503, "修改失败", null);
    }

    @GetMapping("/login")
    public R login(@RequestParam(name = "username") String username, @RequestParam(name = "password") String password) {
        System.out.println("登录的用户名：" + username);
        System.out.println("登录的密码：" + password);
        User user = userDao.selectUserByUserName(username);
        if (user == null) {
            return new R(201, "用户名不存在", null);
        } else if (!user.getPassword().equals(password)) {
            return new R(202, "密码错误", null);
        } else {
            return new R(200, "登录成功", user);
        }
    }
}